<?php
/**
 * Created by IntelliJ IDEA.
 * User: jimmyhsu
 * Date: 2017/5/13
 * Time: 21:35
 */
date_default_timezone_set("Asia/Shanghai");
include('checkLogin.php');
$course_id = $_POST['course_id'];
$file_id = 0;
$sql = "select count(*) as f_count from sharedfile where course_id='$course_id'";
if ($query = mysqli_query($cn, $sql)) {
    $count = mysqli_fetch_array($query)['f_count'];
    if ($count > 0) {
        $sql = "select max(f_id) as max_fid from sharedfile where course_id='$course_id'";
        if ($query = mysqli_query($cn, $sql)) {
            $row = mysqli_fetch_array($query);
            $file_id = $row['max_fid'] + 1;
        }else {
            die ('db_error');
        }
    }
} else {
    die ('db_error');
}


$temp = explode(".", $_FILES["file"]["name"]);
$name = $temp[0];
$extension = end($temp);        // 获取文件后缀名
$file_size = $_FILES["file"]["size"];
if ($file_size < 102400000) { // 小于 100 Mb
    if ($_FILES["file"]["error"] > 0) {
        die("file_error");
    } else {
        $file_name = $file_id . "." . $extension;
        $file_dir = "file/" . $course_id;
        if (!is_dir($file_dir)) {
            mkdir($file_dir, 0777, true);
        }
        if (file_exists($file_dir . "/" . $file_name)) {
            unlink($file_dir . "/" . $file_name);
        }
        if (move_uploaded_file($_FILES["file"]["tmp_name"], $file_dir . "/" . $file_name)) {
            $sql = "insert into sharedfile values('$course_id', $file_id, '$name', $file_size, -1, '"
                . date("Y-m-d H:i:s") . "', '$extension')";
            if (!mysqli_query($cn, $sql)) {
                unlink($file_dir . "/" . $file_name);
                die("db_error");
            } else {
                echo "success";
            }
        } else {
            die("move failed");
        }
    }
} else {
    die("size_exceed");
}
